package com.ylwl.datacenterdemo.service.impl;

import com.ylwl.datacenterdemo.entity.ExcelHeader;
import com.ylwl.datacenterdemo.service.FieldNameGenerator;
import com.ylwl.datacenterdemo.util.TableNameConverter;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;

/**
 * 默认字段名生成器实现
 */
@Component
@RequiredArgsConstructor
public class DefaultFieldNameGenerator implements FieldNameGenerator {
    
    private final TableNameConverter tableNameConverter;
    
    @Override
    public Map<Integer, String> generateFieldNames(List<ExcelHeader> headers) {
        Map<Integer, String> fieldMap = new HashMap<>();
        Set<String> usedFieldNames = new HashSet<>();
        
        for (ExcelHeader header : headers) {
            if (header.isValid()) {
                // 将中文列名转换为拼音作为字段名
                String fieldName = tableNameConverter.convertToTableName(header.getName());
                
                // 确保字段名唯一
                String uniqueFieldName = generateUniqueFieldName(fieldName, usedFieldNames);
                usedFieldNames.add(uniqueFieldName);
                
                // 记录列索引到唯一字段名的映射
                fieldMap.put(header.getIndex(), uniqueFieldName);
                
                // 更新表头的字段名
                header.setFieldName(uniqueFieldName);
            }
        }
        
        return fieldMap;
    }
    
    /**
     * 生成唯一字段名
     * @param baseName 基础名称
     * @param usedNames 已使用的名称集合
     * @return 唯一字段名
     */
    private String generateUniqueFieldName(String baseName, Set<String> usedNames) {
        String uniqueName = baseName;
        int counter = 1;
        while (usedNames.contains(uniqueName)) {
            uniqueName = baseName + "_" + counter;
            counter++;
        }
        return uniqueName;
    }
}